const db = require('../db')
const path = require('path')
var express = require('express');
const { ObjectId } = require('bson');
const createHttpError = require('http-errors');
var router = express.Router();



// 个人空间页面
router.get('/:id', async function (req, res, next) {
  // console.log('req.params', req.params);
  let { id } = req.params;
  let { limit = 5, page = 0 } = req.query;
  // console.log('limit', limit);
  try {
    id = new ObjectId(id)
    // console.log('id', id);
  } catch (error) {
    return next(createError(404, '页面不存在'))
  }
  // 根据ID查找用户信息
  const user = await db.findOneUser({ _id: id })

  // 根据用户信息  查找文章
  const posts = await db.findPost({ authorId: id }, { limit: Number(limit), skip: limit * page })
  // console.log('posts', posts);

  // console.log('result', result);
  res.render('user', { title: '个人空间', user, ...posts })
});

// // 进入修改个人资料页面
router.get('/:id/profile', async function (req, res, next) {
  let { id } = req.params;
  try {
    id = new ObjectId(id)
    // console.log('id', id);
  } catch (error) {
    // return next(createError(404, '您访问的页面不存在！'))
  }
  // 根据ID查找 用户信息
  const user = await db.findOneUser({ _id: id })
  if (!user) {
    // return next(createError(404, '该页面不存在'))
  }
  // 根据用户信息 找到 文章信息
  const posts = await db.findPost({ authorId: id })
  res.render('user-profile', { title: '修改资料', user, ...posts })
});
// 提交修改个人信息的数据
router.post('/:id/profile', async function (req, res, next) {
  let { id } = req.params;
  try {
    id = new ObjectId(id)

    // 根据ID 查找用户
    let user = await db.findOneUser({ _id: id })
    console.log('user', user);

    let { sex, intro } = req.fields;
    let { img } = req.files;
    // console.log('sex', sex, 'intro', intro, 'img', img);
    img = img.size > 0 ? `/upload/${path.win32.basename(img.path)}` : user.avatar;

    // 保存到数据库
    await db.updateOneUser({ _id: id }, { $set: { sex, intro, avatar: img } })
    req.flash('success', '修改成功')
    res.redirect('back')
  } catch (error) {
    console.log('出错了');
    console.log('error', error);
  }




});
module.exports = router;
